import json
import threading
import time

import requests
# from memory_profiler import profile

from logger import log


class Settings:
    def __init__(self):
        self.streams = None
        self.platformId = None
        self.platformName = None
        self.name = None
        self.code = None
        self.force_codec = None
        self.id = None
        self.host = None
        self.vs_host = None
        self.mqtt_server_uri = None
        self.mqtt_username = None
        self.mqtt_password = None
        self.vm_write_url = None

    def getConfig(self):
        while True:
            try:
                response = requests.get("https://" + self.host + "/api/weigh/internal/vsEdge/getByCode/" + self.code)
                ctx = response.text
                loads = json.loads(ctx)
                self.id = loads['data']['id']
                self.name = loads['data']['name']
                self.platformId = loads['data']['platformId']
                self.platformName = loads['data']['platformName']
                self.mqtt_server_uri = loads['data']['mqttServerUri']
                self.mqtt_username = loads['data']['mqttUserName']
                self.mqtt_password = loads['data']['mqttPassword']
                self.streams = loads['data']['ids']
                # log.info(f"配置加载完成:{loads}")
            except Exception as e:
                pass
            time.sleep(60)

    # @profile
    def init(self, code, host="platform.wechain360.com", force_codec=None, vs_host=None):
        self.host = host
        self.code = code
        self.force_codec = force_codec
        # 先执行一次再进入循环；
        response = requests.get("https://" + self.host + "/api/weigh/internal/vsEdge/getByCode/" + self.code)
        ctx = response.text
        loads = json.loads(ctx)
        self.id = loads['data']['id']
        self.name = loads['data']['name']
        self.platformId = loads['data']['platformId']
        self.platformName = loads['data']['platformName']
        self.mqtt_server_uri = loads['data']['mqttServerUri']
        self.mqtt_username = loads['data']['mqttUserName']
        self.mqtt_password = loads['data']['mqttPassword']
        self.vm_write_url = loads['data']['vmUrl']
        self.streams = loads['data']['ids']
        self.vs_host = vs_host

        thread = threading.Thread(target=self.getConfig)
        thread.start()


settings = Settings()

if __name__ == '__main__':
    settings.init("vs_1", "platform.sxgjwl.com")
    print(settings.streams)
